package archive

import (
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
)

type Task struct {
	Files      []string
	Id         string
	Status     int
	OutputFile string
}

type TaskReq struct {
	Files  []string `json:"files,omitempty"`
	Status string
}

type TaskResp struct {
	Id     string `json:"id,omitempty"`
	Status string `json:"status,omitempty"`
}

// 创建任务
func archiveFileTask(ctx server.Context) {

	var req TaskReq
	var resp app.ResponseWrapper
	var err error

	err = ctx.C.ReadJSON(&req)
	if err != nil {
		log.Info(err)
		resp.Code = 500
		ctx.Json(resp)
		return
	}

	bs, err := json.Marshal(req)
	if err != nil {
		log.Info(err)
		resp.Code = 500
		ctx.Json(resp)
		return
	}
	shaHandler := sha256.New()
	shaHandler.Write(bs)
	bs = shaHandler.Sum(nil)
	sha := fmt.Sprintf("%02x", bs)
	if exists, status := checkTaskExists(sha); exists {
		log.Info("task exist")
		var task = TaskResp{Id: sha, Status: status}
		resp.Data = task
		resp.Code = 200
		ctx.Json(resp)
		return
	}

	createTask(sha, req.Files...)
	log.Info("task exist")
	var task = TaskResp{Id: sha, Status: "init"}
	resp.Data = task
	resp.Code = 200
	ctx.Json(resp)
}

// id: status
var taskFactory = make(map[string]TaskReq)

func checkTaskExists(id string) (exists bool, status string) {
	task, exists := taskFactory[id]
	if exists {
		status = task.Status
	}
	return
}

func createTask(id string, files ...string) {
	task := TaskReq{Status: "init", Files: files}
	taskFactory[id] = task
	// TODO
}
